import { writeFile, mkdir } from 'fs/promises'
import { NextRequest, NextResponse } from 'next/server'
import path from 'path'
import { getUser } from '@/lib/authUtils'
import { checkStorageLimit, updateStorageUsage } from '@/lib/limitChecker'
import { existsSync } from 'fs'

export async function POST(request: NextRequest) {
    console.log("开始处理文件上传请求")
    try {
        // 验证用户身份
        const userId = await getUser(request);
        if (!userId) {
            return NextResponse.json({ error: '未授权访问' }, { status: 401 });
        }
        if (userId instanceof NextResponse) {
            return userId;
        }

        console.log("正在读取文件数据...")
        const file = request.body
        const contentType = request.headers.get("content-type") || "application/octet-stream"
        const fileName = request.headers.get("x-vercel-filename") || "image.png"

        if (!file) {
            console.log("错误：未检测到文件")
            return NextResponse.json({ success: false, message: "请选择文件" })
        }

        console.log(`接收到文件: ${fileName}, 类型: ${contentType}, 用户: ${userId}`)

        // 读取文件内容
        const arrayBuffer = await new Response(file).arrayBuffer()
        const buffer = Buffer.from(arrayBuffer)
        const fileSizeBytes = buffer.length
        console.log(`buffer大小: ${fileSizeBytes} bytes`)

        // 检查存储限制
        const storageCheck = await checkStorageLimit(userId, fileSizeBytes);
        if (!storageCheck.allowed) {
            return NextResponse.json({
                success: false,
                error: '存储空间不足',
                details: {
                    currentUsage: storageCheck.currentUsage,
                    limit: storageCheck.limit,
                    planType: storageCheck.planType,
                    fileSize: Math.ceil(fileSizeBytes / (1024 * 1024))
                }
            }, { status: 413 });
        }

        // 构建用户专属的上传目录路径
        const uploadDir = path.join(process.cwd(), 'uploads', 'users', userId, 'image')
        console.log(`上传目录: ${uploadDir}`)
        
        // 确保目录存在
        if (!existsSync(uploadDir)) {
            await mkdir(uploadDir, { recursive: true })
            console.log(`创建目录: ${uploadDir}`)
        }
        
        // 生成唯一文件名
        const uniqueFilename = `${Date.now()}-${fileName}`
        const filePath = path.join(uploadDir, uniqueFilename)
        console.log(`完整文件路径: ${filePath}`)
        
        // 写入文件
        console.log("开始写入文件...")
        await writeFile(filePath, buffer)
        console.log("文件写入成功")

        // 更新用户存储使用量
        await updateStorageUsage(userId, fileSizeBytes);

        // 构建访问URL（使用用户目录结构）
        const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || ''
        const fileUrl = `${baseUrl}/api/uploads/users/${userId}/image/${uniqueFilename}`
        console.log(`文件访问URL: ${fileUrl}`)
        
        return NextResponse.json({
            success: true,
            url: fileUrl,
            fileInfo: {
                name: fileName,
                type: contentType,
                path: filePath,
                size: fileSizeBytes,
                sizeMB: Math.ceil(fileSizeBytes / (1024 * 1024)),
                userId
            }
        });

    } catch (error) {
        console.error("文件上传错误:", error)
        return NextResponse.json({
            success: false,
            message: "文件上传失败",
            error: error instanceof Error ? error.message : "未知错误"
        }, { status: 500 })
    }
}